<template>
	<view class="content">
		<view id="canvas" class="canvas" :prop="newVal" :change:prop="canvas.create"></view>
	</view>
</template>

<!-- 逻辑层script -->
<script>
	import { useCheckType } from "../../../lib/ts/util"
	
	const { check } = useCheckType()
	
	export default {
		data() {
			return {
				newVal: null,
			};
		},
		methods: {
			create(path){
				if(check(path,'video')){
					this.newVal = {fullurl:path, width: 300, height: 300}
				}else{ //非视频路径直接返回
					this.$emit('success',path)
				}
			},
			getUrl(url){ //逻辑层接收路径
				this.$emit('success',url)
			}
		}
	}
</script>

<!-- 视图层script module对应HTML代码中view的id-->
<script module="canvas" lang="renderjs">
	export default {
		methods: {
			create(newValue, oldValue, ownerInstance){
				// 第一次进入为空不操作
				if(!newValue) return
				var video = document.createElement("VIDEO")
				video.autoplay = true
				video.muted = true
				video.setAttribute('crossOrigin', 'anonymous')
				video.crossOrigin = '*'
				video.innerHTML = '<source src=' + newValue.fullurl + ' type="audio/mp4">'
				var canvas = document.createElement('canvas');
				var ctx = canvas.getContext('2d');
				video.play()
				video.addEventListener('canplay', (e)=>{
					//获取视频真实宽高及截取坐标
					let videoWidth = e.target.videoWidth
					let videoHight = e.target.videoHeight
					let sort = Math.min(videoWidth,videoHight)
					let y = 0
					let x = 0
					let difference = Math.floor((videoHight-videoWidth)/2)
					if(difference<0) x = Math.abs(difference)
					else y = Math.abs(difference)
					
					// 创建画布的宽高属性节点，就是图片的大小，单位PX
					var anw = document.createAttribute("width");
					anw.nodeValue = newValue.width;
					var anh = document.createAttribute("height");
					anh.nodeValue = newValue.height;
					canvas.setAttributeNode(anw);
					canvas.setAttributeNode(anh);
					// 画布渲染
					ctx.drawImage(video,x,y,sort,sort,0, 0,newValue.width,newValue.height);
					var base64 = canvas.toDataURL('image/jpeg')
					//转为临时路径
					let url = URL.createObjectURL(this.base64ToBlob(base64))
					ownerInstance.callMethod('getUrl',url)
					video.remove()
				})
			},
			base64ToBlob:(base64Data) =>{
			    let arr = base64Data.split(','),
			        type = arr[0].match(/:(.*?);/)[1],
			        bstr = atob(arr[1]),
			        l = bstr.length,
			        u8Arr = new Uint8Array(l);
			    while (l--) {
			        u8Arr[l] = bstr.charCodeAt(l);
			    }
			    return new Blob([u8Arr], {
			        type
			    })
			}
		}
	}
</script>


<style scoped lang="scss">
	.canvas{
		display: none;
	}

</style>